package pt.ipleiria.plp.ui;

import de.enough.polish.ui.Alert;
import de.enough.polish.ui.AlertType;
import de.enough.polish.ui.ChoiceGroup;
import de.enough.polish.ui.Command;
import de.enough.polish.ui.CommandListener;
import de.enough.polish.ui.Displayable;
import de.enough.polish.ui.Form;
import de.enough.polish.ui.StringItem;
import de.enough.polish.ui.TextField;
import de.enough.polish.util.Locale;
import java.io.IOException;
import pt.ipleiria.plp.BlackSpotterMidlet;
import pt.ipleiria.plp.threads.CallbackValidKey;

/**
 *
 * @author Ricardo
 */
public class OpcoesScreen extends Form implements CommandListener, CallbackValidKey {

    private static final String[] workModes = {"online", "offline"};
    private BlackSpotterMidlet midlet;
    OnHold hold;
    private Command cmdProx = new Command(Locale.get("cmd.Guardar"), Command.OK, 1);
    private Command cmdExit = new Command(Locale.get("cmd.Cancelar"), Command.CANCEL, 3);
    //#style itemInput
    private TextField definirChave = new TextField(Locale.get("label.AppKeyLabel"), "", 25, TextField.ANY);
    //#style horizontalChoice
    private ChoiceGroup mode = new ChoiceGroup(Locale.get("label.envMode"), ChoiceGroup.POPUP, workModes, null);

    public OpcoesScreen(BlackSpotterMidlet midlet) {
        //#style defaultScreen
        super(Locale.get("title.Opcoes"));

        this.midlet = midlet;
        this.setCommandListener(this);

        this.append(definirChave);
        this.append(mode);


        this.addCommand(cmdProx);
        this.addCommand(cmdExit);

    }

    public void commandAction(Command c, Displayable d) {
        if (c == cmdProx) {
            if (definirChave.getString() != null) {
                midlet.getApp().validateAppKey(definirChave.getString(), this);
                hold = new OnHold(midlet, this);
            }

        }
        midlet.getDisplay().setCurrent(midlet.getMainMenu());
    }

    public void returnValidation(boolean valid) {
        if (valid) {
            try {
                midlet.getApp().setAppKey(definirChave.getString());
                Alert alert = new Alert(Locale.get("title.sucesso"),
                        Locale.get("mensagens.sucesso"), null, AlertType.INFO);
                midlet.getDisplay().setCurrent(alert, midlet.getMainMenu());
            } catch (IOException ex) {
                ex.printStackTrace();
                Alert alert = new Alert(Locale.get("title.Erro"),
                        Locale.get("mensagem.sysError"), null, AlertType.ERROR);
                midlet.getDisplay().setCurrent(alert, midlet.getMainMenu());
            }
        } else {
            Alert alert = new Alert(Locale.get("title.Erro"),
                    Locale.get("mensagem.appInvalida"), null, AlertType.ERROR);
            midlet.getDisplay().setCurrent(alert, this);
        }
    }
}
